package com.chinasoft04.mall.service.impl;

import com.chinasoft04.mall.mapper.SpManagerAndRoleMapper;
import com.chinasoft04.mall.mapper.SpPermissionMapper;
import com.chinasoft04.mall.service.AuthService;
import com.chinasoft04.mall.dto.AuthL;
import com.chinasoft04.mall.dto.AuthRoleDtoChildrenPermission;
import com.chinasoft04.mall.dto.AuthT;
import com.chinasoft04.mall.pojo.AuthMainTab;
import com.chinasoft04.mall.pojo.AuthPermissionPlus;
import com.chinasoft04.mall.dto.AuthRoleDto;
import com.chinasoft04.mall.pojo.AuthRolePojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    SpPermissionMapper spPermissionMapper;
    @Autowired
    SpManagerAndRoleMapper spManagerAndRoleMapper;

    @Override
    public List<AuthMainTab> getMainTabByIds(String ids) {
        if(ids==null||ids.length()==0)return null;
        List<AuthPermissionPlus> allAuthPermissionPlusBefore = spPermissionMapper.getAllAuthPermissionPlus();
        //根据ids提取需要的功能
        String[] ids2 = ids.split(",");
        List<AuthPermissionPlus> allAuthPermissionPlus = new ArrayList<>();
        for (String s : ids2) {
            for (AuthPermissionPlus one : allAuthPermissionPlusBefore) {
                if(one.getPs_id() == Integer.parseInt(s))allAuthPermissionPlus.add(one);
            }
        }
        ArrayList<AuthMainTab> tabList = new ArrayList<>();
        Integer flag2 = 0;
        while(true){
            flag2+=1;
            if(allAuthPermissionPlus.size()==0)break;
            if(flag2==20){
                System.out.println("Error!");
                break;
            }
            for (int i = 0; i<allAuthPermissionPlus.size(); i++){
                AuthPermissionPlus perm = allAuthPermissionPlus.get(i);
                Integer flag = 0;
                //先把东西抽出来变成tab
                AuthMainTab newTab = new AuthMainTab();
                newTab.setId(perm.getPs_id());
                newTab.setAuthName(perm.getPs_name());
                newTab.setChildren(new ArrayList<AuthMainTab>());
                newTab.setPath(perm.getPs_api_path());
                //抽出来变成tab后，再根据剩余的东西把tab拼在列表里
                if (perm.getPs_level() == 0) {
                    tabList.add(newTab);
                    flag = 1;
                } else if (perm.getPs_level() == 1) {
                    //遍历标签列表
                    for (AuthMainTab mainTab : tabList) {
                        //找到宿主列表
                        if (Objects.equals(mainTab.getId(), perm.getPs_pid())) {
                            if(mainTab.getChildren()==null){
                                List<AuthMainTab> children = new ArrayList<>();
                                children.add(newTab);
                                mainTab.setChildren(children);
                            }
                            else mainTab.getChildren().add(newTab);
                            flag = 1;
                        }
                    }
                } else if (perm.getPs_level() == 2) {
                    for (AuthMainTab mainTab : tabList) {
                        //Chilren.size>0
                        if (mainTab.getChildren() != null && mainTab.getChildren().size() != 0)
                            for (AuthMainTab child : mainTab.getChildren()) {
                                //Chilren.size>0
                                if (child.getChildren() != null && child.getChildren().size() != 0){
                                    child.getChildren().add(newTab);
                                    flag = 1;
                                }
                                else {
                                    ArrayList<AuthMainTab> authMainTabs = new ArrayList<>();
                                    authMainTabs.add(newTab);
                                    flag = 1;
                                }
                            }
                        else {   //chilren不存在或者为0

                        }
                    }
                }
                if(flag == 1){
                    allAuthPermissionPlus.remove(i);
                    i-=1;
                }
            }
        }
        return tabList;
    }

    @Override
    public String getPsIdsByMgId(Integer mg_id) {
        String ids = spManagerAndRoleMapper.getPsIdsByMgId(mg_id);
        return ids;
    }

    @Override
    public List<AuthRoleDto> getAllRoleWithChildren() {
        List<AuthRolePojo> rolePojos = spManagerAndRoleMapper.getAllRole();
        List<AuthRoleDto> roleDtos = new ArrayList<>();
        for (AuthRolePojo rolePojo : rolePojos) {
            AuthRoleDto roleDto = getRoleDtoWithChildrenByRoleId(rolePojo.getRole_id());
            roleDtos.add(roleDto);
        }
        return roleDtos;
    }

    @Override
    public boolean addRole(AuthRoleDto roleDto) {
        AuthRolePojo rolePojo = new AuthRolePojo();
        rolePojo.setRole_desc(roleDto.getRoleDesc());
        rolePojo.setRole_name(roleDto.getRoleName());
        Integer i = spManagerAndRoleMapper.addRole(rolePojo);
        if(i==0)return false;
        return true;
    }

    @Override
    public AuthRoleDto getRoleDtoByRoleIdWithoutChildren(Integer id) {
        AuthRolePojo rolePojo = spManagerAndRoleMapper.getRoleByRoleId(id);
        if(rolePojo==null)return null;
        AuthRoleDto roleDto = new AuthRoleDto(rolePojo);
        return roleDto;
    }

    @Override
    public boolean updateRoleByRoleId(AuthRoleDto roleDto) {
        AuthRolePojo rolePojo = new AuthRolePojo(roleDto);
        System.out.println(rolePojo);
        int i = spManagerAndRoleMapper.updateRoleByRoleId(rolePojo);
        if(i==1)return true;
        return false;
    }

    @Override
    public boolean deleteRoleByRoleId(Integer id) {
        int i = spManagerAndRoleMapper.deleteRoleByRoleId(id);
        if(i==1)return true;
        return false;
    }

    @Override
    public List<AuthL> getPermissionByList(Integer mg_id) {
        //获得权限详情: perm_ids
        String[] perm_ids = spManagerAndRoleMapper.getPsIdsByMgId(mg_id).split(",");
        //产生列表
        List<AuthL> authLList = new ArrayList<>();
        for (String perm_id : perm_ids) {
            AuthPermissionPlus permPlus = spPermissionMapper.getPermissionPlusById(Integer.parseInt(perm_id));
            if(permPlus==null) {
                System.out.println("不存在的perm_id: " + perm_id);
            }
            else {
                AuthL authL = new AuthL(permPlus);
                authLList.add(authL);
            }
        }
        return authLList;
    }

    @Override
    public List<AuthT> getPermissionByTree() {
        List<AuthPermissionPlus> perms = spPermissionMapper.getAllAuthPermissionPlus();
        List<AuthT> authTList = new ArrayList<>();
        int flag2 = 0;
        while(true){
            flag2+=1;
            if(flag2==20){
                System.out.println("warn: getPermissionByTree's auths are surplus");
                break;
            }
            for (int i = 0; i < perms.size(); i++) {
                AuthPermissionPlus perm = perms.get(i);
                if(perm==null)continue;
                int level = perm.getPs_level();
                AuthT authT = new AuthT();
                authT.setId(perm.getPs_id());
                authT.setAuthName(perm.getPs_name());
                authT.setPath(perm.getPs_api_path());
                authT.setPid(perm.getPs_pid());
                authT.setChildren(new ArrayList<>());
                //等级为0
                if(level==0){
                    authTList.add(authT);
                    perms.remove(i--);
                //等级为1
                }else if(level==1){
                    //遍历父标签
                    for (AuthT t : authTList) {
                        //匹配到对应的父标签
                        if(Objects.equals(t.getId(), perm.getPs_pid())){
                            t.getChildren().add(authT);
                            perms.remove(i--);
                        }
                    }
                //等级为2
                }else if(level==2){
                    //遍历父标签
                    for (AuthT t : authTList) {
                        //遍历二级父标签
                        if(t.getChildren()!=null && t.getChildren().size()!=0)
                        for (AuthT child : t.getChildren()) {
                            //匹配到对应的父标签
                            if(Objects.equals(child.getId(), perm.getPs_pid())){
                                child.getChildren().add(authT);
                                perms.remove(i--);
                            }
                        }
                    }
                }
            }
        }
        return authTList;
    }

    @Override
    public boolean replaceAuthByRidsAndRoleId(Integer roleId, String rids) {
        int i = spManagerAndRoleMapper.replaceAuthByRidsAndRoleId(roleId, rids);
        if(i==1)return true;
        return false;
    }

    @Override
    public boolean deleteAAuthByRoleIdAndRightId(Integer roleId, Integer rightId) {
        AuthRolePojo rolePojo = spManagerAndRoleMapper.getRoleByRoleId(roleId);
        String ids = rolePojo.getPs_ids();
        int i = ids.indexOf("," + rightId);
        if(i==-1){
            i = ids.indexOf(rightId.toString());
            if(i==-1){
                System.out.println("Error: deleteAAuthByRoleIdAndRightId's rightId is not found");
                return false;
            }
            else{
                ids = ids.replace(rightId.toString(), "");
            }
        }else{
            ids = ids.replace( "," +rightId, "");
        }
        int n = spManagerAndRoleMapper.replaceAuthByRidsAndRoleId(roleId, ids);
        if(n==1)return true;
        System.out.println("Error: deleteAAuthByRoleIdAndRightId's replace failed");
        return false;
    }

    @Override
    public int checkAuthByRole(Integer roleId) {
        int i = 0;
        int n = 0;
        AuthRoleDto roleDto;
        while (true) {
            i+=1;
            List<String> unusefullAuth = new ArrayList<>();
            roleDto = getRoleDtoWithChildrenByRoleId(roleId);
            //在该角色里遍历出需要剔除的id
            if(roleDto.getChildren()!=null && roleDto.getChildren().size()!=0)
            {
                //0级目录
                for (AuthRoleDtoChildrenPermission child : roleDto.getChildren()) {
                    //1级目录
                    if (child.getChildren() == null || child.getChildren().size() == 0) {
                        //1级目录没有孩子，加入剔除列表
                        unusefullAuth.add(new String(child.getId().toString()));
                    } else {
                        List<AuthRoleDtoChildrenPermission> children = child.getChildren();
                        //2级目录
                        for (AuthRoleDtoChildrenPermission child02 : children) {
                            if (child02.getChildren() == null || child02.getChildren().size() == 0) {
                                //1级目录没有孩子，加入剔除列表
                                unusefullAuth.add(new String(child02.getId().toString()));
                            }
                        }
                    }
                }
            }
            for (String s : unusefullAuth) {
                boolean b = deleteAAuthByRoleIdAndRightId(roleDto.getRoleId(), Integer.parseInt(s));
                if (!b) System.out.println("剔除失败!");
                else n += 1;
            }
            if(i==2)break;
        }
        return n;
    }

    @Override
    public AuthRoleDto getRoleDtoWithChildrenByRoleId(Integer roleId) {
        AuthRolePojo rolePojo = spManagerAndRoleMapper.getRoleByRoleId(roleId);
        AuthRoleDto roleDto = new AuthRoleDto(rolePojo);
        //开始为children封装
        if(rolePojo.getPs_ids()!=null&&!rolePojo.getPs_ids().equals(""))
        {
            List<AuthRoleDtoChildrenPermission> children = new ArrayList<>();
            //取得idsList
            String[] ids = rolePojo.getPs_ids().split(",");
            //把需要的perm全部从数据库里取出来
            List<AuthPermissionPlus> permPlusList = new ArrayList<>();
            for (int i = 0; i < ids.length; i++) {
                Integer id = Integer.parseInt(ids[i]);
                AuthPermissionPlus authPermissionPlus = spPermissionMapper.getPermissionPlusById(id);
                permPlusList.add(authPermissionPlus);
            }
            //根据perm的排序，封装为children
            {
                int flagFinish = 0;
                while(true){
                    flagFinish+=1;
                    if(flagFinish==20){
                        System.out.println("warn: getAllRoleWithChildren's auths are surplus.");
                        System.out.println(permPlusList);
                        break;
                    }
                    //清除多出来的null
                    if(permPlusList.get(0)==null)permPlusList.remove(0);
                    //遍历一次所有需要的perm, 把能编入的perm都编入到children里
                    for (int i = 0; i < permPlusList.size(); i++) {
                        AuthPermissionPlus perm = permPlusList.get(i);
                        if(perm==null)continue;
                        AuthRoleDtoChildrenPermission child = new AuthRoleDtoChildrenPermission();
                        child.setId(perm.getPs_id());
                        child.setAuthName(perm.getPs_name());
                        child.setPath(perm.getPs_api_path());
                        child.setChildren(new ArrayList<AuthRoleDtoChildrenPermission>());
                        int level = perm.getPs_level();
                        if(level==0){
                            //等级为0
                            children.add(child);
                            //移除该perm
                            permPlusList.remove(i--);
                        }else if(level==1){
                            //等级为1
                            //遍历父节点
                            for (AuthRoleDtoChildrenPermission child00 : children) {
                                if(Objects.equals(child00.getId(), perm.getPs_pid())){
                                    //找到了父节点
                                    child00.getChildren().add(child);
                                    //移除该perm
                                    permPlusList.remove(i--);
                                }
                            }
                        }else{
                            //等级为2
                            //遍历父节点
                            for (AuthRoleDtoChildrenPermission child00 : children) {
                                //遍历次节点
                                if(child00.getChildren()!=null && child00.getChildren().size()!=0)
                                    for (AuthRoleDtoChildrenPermission child01 : child00.getChildren()) {
                                        if(Objects.equals(child01.getId(), perm.getPs_pid())){
                                            //找到了目标节点
                                            child01.getChildren().add(child);
                                            //移除该perm
                                            permPlusList.remove(i--);
                                        }
                                    }
                            }
                        }
                    }
                    if(permPlusList.size()==0 || permPlusList==null){
                        //permList已遍历完成
                        break;
                    }
                }
            }
            roleDto.setChildren(children);
        }
        return roleDto;
    }
}
